'use strict'
const {Blogs,Op}=require('../model')
let fn_index =async(ctx,next)=>{
    let keyword = ctx.request.query.keyword
    console.log(keyword);
    let obj  =ctx.request.body
    if(keyword){
        let list = await Blogs.findAll({
            where:{
                [Op.or]:[
                    {title:keyword},
                    {digest:keyword},
                    {content:keyword},
                    {class:keyword},
                    {author:keyword}
                ]
            }
        })
        ctx.body=list
    }else{
        let list = await Blogs.findAll({
            order:[['id','asc']]
        })
        console.log(list);
        ctx.body=list
    }
}
let fn_add =async(ctx,next)=>{
    let obj = ctx.request.body
    console.log(obj);
    if(obj){
        let tmpobj = {
            title:obj.title,
            digest:obj.digest,
            content:obj.content,
            class:obj.classs,
            author:obj.author

        }
        await Blogs.create(tmpobj)
        ctx.body={
            code:1000,
            data:tmpobj,
            msg:''
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'错误异常'
        }
    }
}
let fn_delete =async(ctx,next)=>{
    let id = ctx.request.params.id
    let blogs = await Blogs.findByPk(id)
    if(blogs){
        await Blogs.destroy({
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:{id:id},
            msg:''
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'错误异常'
        }
    }
}
let fn_edit =async(ctx,next)=>{
    let id = ctx.request.params.id

    let obj = ctx.request.body
    let blogs = await Blogs.findByPk(id)
    if(blogs){
        await Blogs.update(obj,{
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:obj,
            msg:''
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'错误异常'
        }
    }
}
module.exports={
    'get /blogs':fn_index,
    'post /blogs':fn_add,
    'put /blogs/:id':fn_edit,
    'delete /blogs/:id':fn_delete,
}